import { MenuProps } from "antd";
import router from "../routes";

// 辅助函数：查找匹配的路由
function findRoute(routes: any[], path: string): any | null {
  for (const route of routes) {
    if (route.path) {
      const fullPath = route.path.startsWith("/")
        ? route.path
        : `/${route.path}`;
      if (fullPath === path) {
        return route;
      }
    }
    if (route.children) {
      const childRoute = findRoute(route.children, path);
      if (childRoute) {
        return childRoute;
      }
    }
  }
  return null;
}
// 辅助函数：生成面包屑项
function generateBreadcrumbs(
  pathname: string
): { path: string; breadcrumbName: string }[] {
  const pathSegments = pathname.split("/").filter((segment) => segment);
  const breadcrumbs: { path: string; breadcrumbName: string }[] = [];
  let currentPath = "";

  for (const segment of pathSegments) {
    currentPath =
      currentPath === "" ? `/${segment}` : `${currentPath}/${segment}`;
    const route = findRoute(router.routes, currentPath);
    if (route && route.breadcrumbName) {
      breadcrumbs.push({
        path: currentPath,
        breadcrumbName: route.breadcrumbName,
      });
    }
  }

  return breadcrumbs;
}

type MenuItem = Required<MenuProps>["items"][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[]
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

// 辅助函数：根据路由生成菜单项
function generateMenuItems(routes: any[]): MenuItem[] {
  return routes
    .filter((route) => route.path !== "*")
    .map((route) => {
      let itemKey = route.path;
      if (route.index) {
        itemKey = "/";
      }
      if (route.children) {
        return getItem(
          route.breadcrumbName || route.path,
          itemKey,
          route.icon,
          generateMenuItems(route.children)
        );
      }
      return getItem(route.breadcrumbName || route.path, itemKey, route.icon);
    });
}

export { findRoute, generateBreadcrumbs, getItem, generateMenuItems };
